const path = require("path");
const multer = require("multer");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const assert = require("http-assert");

const rest = require("./rest");
const AdminUser = require("../../models/AdminUser");
const authMiddleware = require("../../middleware/auth");
const resourceMiddleware = require("../../middleware/resource");

module.exports = (app) => {
  app.use(
    "/admin/api/rest/:resource",
    // authMiddleware(),
    resourceMiddleware(),
    rest
  );

  const upload = multer({ dest: path.resolve(__dirname, "../../uploads") });
  app.post(
    "/admin/api/upload",
    authMiddleware(),
    upload.single("file"),
    async (req, res) => {
      const file = req.file;
      file.url = `http://localhost:3000/uploads/${file.filename}`;
      res.send(file);
    }
  );

  app.post("/admin/api/login", async (req, res) => {
    const { username, password } = req.body;
    const user = await await AdminUser.findOne({ username }).select(
      "+password"
    );
    assert(user, 422, "用户不存在");
    const isValid = bcrypt.compareSync(password, user.password);
    assert(isValid, 422, "密码错误");
    const token = jwt.sign(
      {
        id: user._id,
        _id: user._id,
      },
      app.get("secret"),
      { expiresIn: 2 * 60 * 60 }
    );
    res.send({ token });
  });

  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      message: err.message,
    });
  });
};
